import {NextRequest, NextResponse} from "next/server";
import fs from "fs/promises";
import path from "path";
import {
  RecordProps,
  RecordsRequestProps,
  RecordsResponseProps,
  FilterProps,
} from "@/components/IpdTable/interface";

// 排序函数
const sortData = (
  data: RecordProps[],
  column: keyof RecordProps,
  direction: "asc" | "desc",
): RecordProps[] => {
  return data.sort((a, b) => {
    if (a[column] < b[column]) return direction === "asc" ? -1 : 1;
    if (a[column] > b[column]) return direction === "asc" ? 1 : -1;
    return 0;
  });
};

// 筛选函数（仅添加）
const filterData = (data: RecordProps[], filter: FilterProps): RecordProps[] => {
  return data.filter((record) => {
    return (
      // 如果 filter 值为空（空字符串或 null），则跳过筛选该字段
      (filter.type === null || record.type === filter.type) &&
      (filter.name === "" || record.name.includes(filter.name)) &&
      (filter.oaId === "" || record.oaId === filter.oaId) &&
      (filter.state === null || record.stage === filter.state) &&
      (filter.createdByUserName === "" ||
        record.createdByUserName.includes(filter.createdByUserName)) &&
      (filter.executedByUserName === "" ||
        record.executedByUserName.includes(filter.executedByUserName)) &&
      (filter.reviewedByUserName === "" ||
        record.reviewedByUserName.includes(filter.reviewedByUserName))
    );
  });
};

export async function POST(request: NextRequest) {
  try {
    // 解析请求体
    const {
      page = 1,
      pageSize = 10,
      filter = {
        type: null,
        name: "",
        oaId: "",
        state: null,
        createdByUserName: "",
        executedByUserName: "",
        reviewedByUserName: "",
      },
      sortStatus = {columnAccessor: "createdTime", direction: "asc"}, // 添加默认值
    }: RecordsRequestProps = await request.json();

    // 读取数据文件，文件存放位置：/public/mock/simuProj.json
    const filePath = path.join(process.cwd(), "public", "mock", "simuProj.json");
    const data = await fs.readFile(filePath, "utf-8");
    const records: RecordProps[] = JSON.parse(data);

    // 筛选数据（新增逻辑）
    const filteredRecords = filterData(records, filter);

    // 排序数据（根据前端传递的sortStatus）
    const sortedRecords = sortStatus
      ? sortData(
          filteredRecords,
          sortStatus.columnAccessor as keyof RecordProps,
          sortStatus.direction,
        )
      : filteredRecords;

    // 分页逻辑
    const totalRecords = sortedRecords.length; // 总记录数
    const startIndex = (page - 1) * pageSize;
    const paginatedRecords = sortedRecords.slice(startIndex, startIndex + pageSize);

    // 返回数据，确保符合 FetchResponse 格式
    const response: RecordsResponseProps = {
      totalRecords,
      records: paginatedRecords,
    };
    console.log(response);

    // 返回分页数据
    return NextResponse.json(response);
  } catch (error) {
    console.log("error");
    return NextResponse.json({error: "获取数据失败"}, {status: 500});
  }
}
